<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Profile/
class Controller_Profile extends Controller_Base 
{
	private $profileService;
	private $postService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		$this->profileService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_PROFILE.'/', ACCESS_TOKEN);
		$this->profileService->init($this->_requestContext);

		$this->postService = new Service_PostServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_POST.'/', ACCESS_TOKEN);
		$this->postService->init($this->_requestContext);
	}
	
	private function loadDefaultContent(&$template)
	{
		// Nothing to do
	}
	
	public function action_index()
	{
		$contentFrame = $this->index('Seednia::Profile', 'default_sbar_right');
		$content = $this->createView('profile_content');
		$contentFrame->content = $content;
		
		$this->template->set_global('enableProjectNavBar',  false);

		try {
			$userXid = $this->getXid();
			$profile = $this->_requestContext->profile;
			if ($userXid != $this->_sessionInfo->userInfo['userSid']) {
				$profile = $this->_profileHelper->getProfile($userXid, 9);
				$this->_profileHelper->setProfileIntoTemplate($this->template, $profile);
			}
			$projectCriteria = array('ownerSid' => $profile->creatorSid);
			$content->projects = $this->_projectHelper->getProjectList($projectCriteria, 0,10);
			
			$postCriteria = array('creatorSid' => $profile->creatorSid, '_retrieveScope'=> 1);
			$content->posts = $this->postService->getPostList($postCriteria, 0, 15);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	}

	/**
	 * User's info 
	 */
	public function action_info()
	{
		$contentFrame = $this->index('Seednia::Profile', 'default_sbar_right');
		$content = $this->createView('profile_info');
		$contentFrame->content = $content;
		
		$this->template->set_global('enableProjectNavBar',  false);

		try {
			$userXid = $this->getXid();
			$profile = $this->_profileHelper->getProfile($userXid, 15); // 2 => fetch full
			$this->_profileHelper->setProfileIntoTemplate($this->template, $profile);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	}
	
	public function action_form()
	{
		if ( $this->isMethodGet() ) {
			$this->showForm();
		} else if ( $this->isMethodPost() ) {
			$this->doUpdate();
		}
	}
	
	private function showForm()
	{
		$contentFrame = $this->index('Seednia::Profile', 'default_sbar_right');
		$content = $this->createView('profile_form');
		$contentFrame->content = $content;
	
		try {
			//$this->_profileHelper->loadProfile($this->template, 9);
			//$this->_projectHelper->loadProject($this->template);

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	}
	
	private function doUpdate()
	{
		try {
			$record = $this->_profileHelper->recordFromForm();
			$record['domainId'] = $this->_requestContext->domainId;

			$this->profileService->update($record);

			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/'.$this->request->controller().'/'.$record['creatorSid'].'/form';
			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	public function action_editeduc()
	{
		$category = 'education';
		if ( $this->isMethodGet() ) {
			$this->showExperienceForm($category);
		} else if ( $this->isMethodPost() ) {
			$this->doExperienceAddOrUpdate($category);
		}
	}

	public function action_editexper()
	{
		$category = 'experience';
		if ( $this->isMethodGet() ) {
			$this->showExperienceForm($category);
		} else if ( $this->isMethodPost() ) {
			$this->doExperienceAddOrUpdate($category);
		}
	}
	
	/**
	 * 
	 * @param type $type 'experience' wor work experience, or 'education' for education
	 */
	private function showExperienceForm($category)
	{
		$contentFrame = $this->index('Seednia::Profile', 'default_sbar_right');
		$content = $this->createView('profile_form_'.$category);
		$contentFrame->content = $content;
	
		try {
			$experienceSid = $this->request->query('sid', null);
			
			$experience = null;
			if ($experienceSid != null && $experienceSid > 0) {
				$experience = $this->profileService->getByXid($experienceSid, 'experience');
			} else {
				$experience = new stdClass;
				$experience->sid = SID_NIL;
				$experience->profileSid = $this->_requestContext->profile->sid;
				$experience->startDate = null;
				$experience->endDate = null;
			}
			$content->experience = $experience;
			
			require_once Kohana::find_file('classes', 'calendarutil');
			$content->ref_months = month_list('us', '--');
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	}
	
	private function doExperienceAddOrUpdate($category)
	{
		try {
			$record = array();
			$record['profileSid'] = $this->request->post('profileSid');
			//$params['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
			$record['sid'] = $this->request->post('sid');
			$record['uuid'] = $this->request->post('uuid');
			$record['categoryName'] = $category;
			$record['type'] = $this->request->post('type');
			$record['organizationSid'] = $this->request->post('organizationSid');
			$record['organizationName'] = $this->request->post('organizationName');
			$record['department'] = $this->request->post('department');
			$record['title'] = $this->request->post('title');
			$record['location'] = $this->request->post('location');
			$record['description'] = $this->request->post('description');
			$record['startDate'] = $this->getDateStr('startDate');
			$record['endDate'] = $this->getDateStr('endDate');
			$record['currently'] = $this->request->post('currently');
			$record['notes'] = $this->request->post('notes');

			if ( isset($record['sid']) && $record['sid'] > 0 ) {
				$this->profileService->update($record, 'experience/');
			} else {
				$this->profileService->add($record, 'experience/');
			}

			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/'.$this->request->controller().'/info/?userSid='.$this->_sessionInfo->userInfo['userSid'];
			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	/**
	 *
	 * @param type $fieldName 'start' or 'end'
	 */
	private function getDateStr($fieldName) {
		$yearPart = $this->request->post($fieldName.'Year');
		
		if ( $yearPart < 100) {
			if ($yearPart > (date("Y")-2000) ) {
				$yearPart = $yearPart + 1900;
			} else {
				$yearPart = $yearPart + 2000;
			}
		}

		$monthPart = $this->request->post($fieldName.'Month');  // add one for zero-index
		if ($monthPart == 0)
			$monthPart = '';
		else if ($monthPart < 10)
			$monthPart = '0'.$monthPart;
		
		return $yearPart.$monthPart;
	}
} // End Controller_Home